<template>
  <div class="app-container">
    <px-form ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="年份">
        <px-date-picker v-model="queryParams.particularYear" type="year" format="YYYY" value-format="YYYY" placeholder="请选择年份" />
      </px-form-item>
      <px-form-item label="交易类型">
        <px-select v-model="queryParams.type" placeholder="请选择" clearable style="width: 240px" filterable>
          <px-option v-for="dict in SourceList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemValue" />
        </px-select>
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>
    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'QUOTATTRADING_ADD'" type="primary" icon="" @click="handleAdd">新增</px-button>
      </px-col>
    </px-row>
    <px-table v-if="!addVisible && !detailVisible" v-loading="loading" :data="typeList" height="calc(100vh - 319px)" show-overflow-tooltip border>
      <px-table-column label="序号" type="index" width="70">
        <template #default="{ $index }">
          {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </px-table-column>

      <px-table-column label="年份" prop="particularYear">
        <template #default="scope">
          <span>{{ scope.row.particularYear }}年</span>
        </template>
      </px-table-column>
      <px-table-column label="交易类型" prop="type">
        <template #default="scope">
          <span v-if="scope.row.type == 'B'" style="color: #10b981">购买</span>
          <span v-else style="color: #ef4444">出售</span>
        </template>
      </px-table-column>
      <px-table-column label="配额交易量 (tCO₂e）" prop="tradeQuota">
        <template #default="scope">
          <span v-if="scope.row.type == 'B'" style="color: #10b981">{{ scope.row.tradeQuota }}</span>
          <span v-else style="color: #ef4444">{{ scope.row.tradeQuota }}</span>
        </template>
      </px-table-column>

      <px-table-column label="配额单价（元/tCO₂e）" prop="price">
        <template #default="scope">
          <span>{{ scope.row.price }}</span>
        </template>
      </px-table-column>
      <px-table-column label="CCER交易量（tCO₂e）" prop="ccerValue">
        <template #default="scope">
          <span v-if="scope.row.type == 'B'" style="color: #10b981">{{ scope.row.ccerValue }}</span>
          <span v-else style="color: #ef4444">{{ scope.row.ccerValue }}</span>
        </template>
      </px-table-column>
      <px-table-column label="CCER单价（元/tCO₂e）" prop="ccerUnitPrice">
        <template #default="scope">
          <span>{{ scope.row.ccerUnitPrice }}</span>
        </template>
      </px-table-column>
      <px-table-column label="交易金额（元）" prop="amount">
        <template #default="scope">
          <span v-if="scope.row.type == 'B'" style="color: #10b981">{{ scope.row.amount }}</span>
          <span v-else style="color: #ef4444">{{ scope.row.amount }}</span>
        </template>
      </px-table-column>
      <px-table-column label="交易人" prop="tradeByName">
        <template #default="scope">
          <span>{{ scope.row.tradeByName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="交易时间" prop="tradeTime">
        <template #default="scope">
          <span>{{ scope.row.tradeTime.split(" ")[0] }}</span>
        </template>
      </px-table-column>
      <px-table-column label="创建人" prop="tradeByName">
        <template #default="scope">
          <span>{{ scope.row.createByName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="创建时间" prop="tradeTime">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="180">
        <template #default="scope">
          <px-button v-has="'QUOTATTRADING_DETAIL'" type="primary" link @click="handleDetail(scope.row.id)">
            <px-tooltip class="box-item" content="详情" placement="top">
              <px-icon>
                <Tickets />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'QUOTATTRADING_VIEW'" type="primary" link @click="handleFileBrowse(scope.row)">
            <px-tooltip class="box-item" content="查看附件" placement="top">
              <px-icon>
                <Browse />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'QUOTATTRADING_EDITOR'" link type="primary" @click="handleEditor(scope.row.id)">
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-has="'QUOTATTRADING_DELETE'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon>
                <Delete />
              </px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />
    <px-scrollbar v-if="detailVisible" class="editorEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="detailVisible = false">返回</px-button>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
      <px-descriptions class="margin-top" style="padding: 20px" title="" :column="2" border>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">交易年份</div>
          </template>
          {{ equipdata.particularYear }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">交易类型</div>
          </template>
          <!-- {{ scope.row.type == 'B' ? '购买' : '出售' }} -->
          <span v-if="equipdata.type == 'B'" style="color: #10b981">购买</span>
          <span v-else style="color: #ef4444">出售</span>
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">配额交易量（tCO₂e）</div>
          </template>
          <span v-if="equipdata.type == 'B'" style="color: #10b981">{{ equipdata.tradeQuota }}</span>
          <span v-if="equipdata.type == 'S'" style="color: #ef4444">{{ equipdata.tradeQuota }}</span>
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">配额单价（元/tCO₂e）</div>
          </template>
          {{ equipdata.price }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">CCER交易量（tCO₂e）</div>
          </template>
          <span v-if="equipdata.type == 'B'" style="color: #10b981">{{ equipdata.ccerValue }}</span>
          <span v-if="equipdata.type == 'S'" style="color: #ef4444">{{ equipdata.ccerValue }}</span>
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">CCER单价（元/tCO₂e）</div>
          </template>
          {{ equipdata.ccerUnitPrice }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">交易金额（元）</div>
          </template>
          <span v-if="equipdata.type == 'B'" style="color: #10b981">{{ equipdata.amount }}</span>
          <span v-if="equipdata.type == 'S'" style="color: #ef4444">{{ equipdata.amount }}</span>
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">交易人</div>
          </template>
          {{ equipdata.tradeByName }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">交易时间</div>
          </template>
          {{ equipdata.tradeTime }}
        </px-descriptions-item>
      </px-descriptions>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">来源文件</div>
      <div class="form-table" style="padding: 20px 20px 0">
        <FileUpload fileType="view" :isPreview="true" :countLimit="1" :fileData="{ moduleName: 'GENERAL_CHEMICALS' }" :fileList="equipdata.files" />
      </div>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">配额分配</div>
      <div style="padding: 0 20px">
        <px-table style="margin-top: 20px" :data="allocationList" height="480px" border>
          <px-table-column label="所属厂区" prop="level">
            <template #default="scope">
              <span>{{ scope.row.level }}</span>
            </template>
          </px-table-column>
          <px-table-column label="交易配额分配" prop="tradeAllocation">
            <template #default="scope">
              <span>{{ scope.row.tradeAllocation }}</span>
            </template>
          </px-table-column>
          <px-table-column label="交易CCER分配" prop="tradeCcer">
            <template #default="scope">
              <span>{{ scope.row.tradeCcer }}</span>
            </template>
          </px-table-column>
        </px-table>
      </div>
    </px-scrollbar>
    <px-scrollbar v-if="addVisible" class="addEquip">
      <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="180px"
      >
        <div
          class="box-card1"
          :style="{
            height: jibenxinxiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">配额信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="12">
                <px-form-item label="交易年份" prop="particularYear">
                  <px-date-picker
                    v-model="equipdata.particularYear"
                    style="width: calc(100% - 70px)"
                    type="year"
                    format="YYYY"
                    value-format="YYYY"
                    placeholder="请选择"
                  />
                  <!-- <px-input v-model="equipdata.particularYear" :maxlength="4" placeholder="请输入" clearable /> -->
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="交易类型" prop="type">
                  <px-radio-group v-model="equipdata.type" class="ml-4" style="margin-top: -5px">
                    <px-radio label="B" size="large">购买</px-radio>
                    <px-radio label="S" size="large">出售</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="配额交易量（tCO₂e）" prop="tradeQuota">
                  <px-input-number
                    v-model="equipdata.tradeQuota"
                    style="width: calc(100% - 70px)"
                    controls-position="right"
                    :max="99999999"
                    :precision="2"
                    placeholder="请输入"
                    clearable
                    @blur="getamount"
                    @change="getamount"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="配额单价（元/tCO₂e）" prop="price">
                  <px-input-number
                    v-model="equipdata.price"
                    style="width: calc(100% - 70px)"
                    controls-position="right"
                    :max="99999999"
                    :precision="2"
                    placeholder="请输入"
                    clearable
                    @blur="getamount"
                    @change="getamount"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="CCER交易量（tCO₂e）" prop="ccerValue">
                  <px-input-number
                    v-model="equipdata.ccerValue"
                    style="width: calc(100% - 70px)"
                    controls-position="right"
                    :max="99999999"
                    :precision="2"
                    placeholder="请输入"
                    clearable
                    @blur="getamount"
                    @change="getamount"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="CCER单价（元/tCO₂e）" prop="ccerUnitPrice">
                  <px-input-number
                    v-model="equipdata.ccerUnitPrice"
                    style="width: calc(100% - 70px)"
                    controls-position="right"
                    :max="99999999"
                    :precision="2"
                    placeholder="请输入"
                    clearable
                    @blur="getamount"
                    @change="getamount"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="交易金额（元）">
                  <px-input-number
                    v-model="equipdata.amount"
                    disabled
                    style="width: calc(100% - 70px)"
                    controls-position="right"
                    :max="99999999"
                    :precision="2"
                    placeholder="自动计算"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="	交易人" prop="tradeByName">
                  <px-select v-model="equipdata.tradeByName" placeholder="请选择" style="width: calc(100% - 70px)" clearable filterable>
                    <px-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.label" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="交易时间" prop="tradeTime">
                  <px-date-picker
                    v-model="equipdata.tradeTime"
                    style="width: calc(100% - 70px)"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    type="date"
                    placeholder="请选择"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>

        <div
          class="box-card2"
          :style="{
            height: jiqicanshuFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setjiqicanshuFlg()">
            <div class="card-title">凭证</div>
            <div class="card-main">
              <px-icon v-if="!jiqicanshuFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div" style="padding: 20px">
            <div class="info-form-content">
              <FileUpload
                fileType="add"
                :fileSize="999"
                fileAccept=".pdf"
                fileTypeValue="pdf"
                :fileData="{ moduleName: 'GENERAL_CHEMICALS' }"
                :fileList="equipdata.files"
                @changeFileList="changeFileList"
                @saveFileStatus="saveFileStatus"
              />
            </div>
          </px-scrollbar>
        </div>
        <div
          class="box-card3"
          :style="{
            height: showAllocation == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setShowAllocation()">
            <div class="card-title">配额分配</div>
            <div class="card-main">
              <px-icon v-if="!showAllocation">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div" style="padding: 20px">
            <div class="info-form-content">
              <px-button type="primary" plain @click="addAllocation">新增厂区</px-button>
            </div>
            <px-table style="margin-top: 20px" :data="allocationList" border>
              <px-table-column label="配额分配厂区" prop="level">
                <template #header> <span style="color: red">*</span><span> 厂区 </span> </template>
                <template #default="scope">
                  <span
                    ><px-select v-model="scope.row.level" placeholder="请选择" clearable filterable>
                      <px-option v-for="item in facList" :key="item.itemName" :label="item.itemName" :value="item.itemValue" /> </px-select
                  ></span>
                </template>
              </px-table-column>
              <px-table-column label="交易配额分配" prop="tradeAllocation">
                <template #header> <span style="color: red">*</span><span> 交易配额分配 </span> </template>
                <template #default="scope">
                  <span
                    ><px-input-number
                      v-model="scope.row.tradeAllocation"
                      controls-position="right"
                      :max="999999999"
                      :min="0"
                      :precision="2"
                      style="width: 200px"
                      placeholder=""
                  /></span>
                </template>
              </px-table-column>
              <px-table-column label="交易CCER分配" prop="tradeCcer">
                <template #header> <span style="color: red">*</span><span> 交易CCER分配 </span> </template>
                <template #default="scope">
                  <span
                    ><px-input-number
                      v-model="scope.row.tradeCcer"
                      controls-position="right"
                      :max="999999999"
                      :min="0"
                      :precision="2"
                      style="width: 200px"
                      placeholder=""
                  /></span>
                </template>
              </px-table-column>
              <px-table-column v-if="!fromdisable" label="操作" align="center" width="280">
                <template #default="scope">
                  <px-button link type="danger" @click="delAllocation(scope.$index)"
                    ><px-tooltip class="box-item" effect="light" content="删除" placement="top">
                      <px-icon><Delete /></px-icon> </px-tooltip
                  ></px-button>
                </template>
              </px-table-column>
            </px-table>
          </px-scrollbar>
        </div>
      </px-form>
    </px-scrollbar>
    <div v-if="addVisible" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button type="primary" @click="equipopenDetailsubmitForm(detailruleFormRef)">保存</px-button>
    </div>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft, Plus } from "@px-ui/icons-vue";
import { useRouter } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { queryListPagepull, queryDetailpull, addpull, updatepull, deletepull, queryListPageForOutbound } from "@/api/hazardousWasteS";
import { quotaquery, quotasave, quotaedit, quotadelete, quotadetail, quotatrial } from "@/api/doubleCarbonManage/quotaManage";
import { quotalistTrade, quotadetailTrade, quotadeleteTrade, quotaupdateTrade } from "@/api/doubleCarbonManage/quotaTrading";
import { queryDictData } from "@/api/common";
import Chart1 from "./chart1.vue";
import Chart2 from "./chart2.vue";
import { userlistPage } from "@/api/waterQualityDetection";
const router = useRouter();
const jibenxinxiFlg = ref(true);
const jiqicanshuFlg = ref(true);
const showAllocation = ref(true);
const trialVisible = ref(false);
const numFlg = ref(true);
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const setShowAllocation = () => {
  showAllocation.value = !showAllocation.value;
};
const setnumFlg = () => {
  numFlg.value = !numFlg.value;
};
const SourceList = [
  {
    itemName: "购买",
    itemValue: "B"
  },
  {
    itemName: "出售",
    itemValue: "S"
  }
];
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const detailruleFormRef = ref();
const addchukuList = () => {
  progressVisible.value = true;
  queryParams2.value.dictWasteCode = "";
  getRukuList();
};
onMounted(() => {
  if (localStorage.getItem("chukuList")) {
  }
});
const handleFileBrowse = row => {
  if (row.files != null) {
    const { id, fileName, moduleName, fileType: type = "" } = row.files[0];
    // doc 暂不支持预览
    const allowType = ["txt", "docx", "xls", "xlsx", "pdf", "png", "jpg", "jpeg", "mp4"];
    if (!allowType.includes(type)) {
      PxMessage.error("暂不支持该格式文件的预览");
      return;
    }
    const path = "/fullScreen/preview";
    const query = { id, fileName, moduleName, type };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    PxMessage.error("没有可以预览的文件");
  }
};
const trialCalculation = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      if (saveFlg(equipdata.value.allocationDTOS)) {
        const params = {
          particularYear: equipdata.value.particularYear,
          price: equipdata.value.price,
          capacity: equipdata.value.capacity,
          createByName: JSON.parse(localStorage.getItem("userInfo")).username,
          updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
          files: equipdata.value.files,
          allocationDTOS: equipdata.value.allocationDTOS
        };
        if (params.files.length > 0) {
          params.files = params.files.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        quotatrial(params).then(res => {
          console.log(res);
          trialVisible.value = true;
          carbonEmissionTrendDTOS.value = res.carbonEmissionTrendDTOS;
          annualQuotaProportionDTO.value = res.annualQuotaProportionDTO;
        });
      } else {
        PxMessage({
          message: `请完善厂区信息`,
          type: "error"
        });
      }
    }
  });
};
const { proxy }: any = getCurrentInstance();
function equipopenDetailcancel() {
  if (buttonTitle.value == "新增") {
    if (
      equipdata.value.particularYear != null ||
      equipdata.value.price != null ||
      equipdata.value.capacity != null ||
      equipdata.value.files.length > 0 ||
      equipdata.value.allocationDTOS.length > 0
    ) {
      PxMessageBox.confirm("<p>取消将不保存当前录入信息返回上一页</p><p>确定取消吗？</p>", "温馨提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          addVisible.value = false;
          getList();
        })
        .catch(() => {});
    } else {
      addVisible.value = false;
      getList();
    }
  } else {
    addVisible.value = false;
    getList();
  }
}
const typeList = ref([]);
const progressVisible = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const addVisible = ref(false);
const detailVisible = ref(false);
const innerVisible = ref(false);
const total = ref(0);
const total2 = ref(0);
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const data = reactive({
  facList: [], // 厂区下拉框
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: [],
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  wasteUnitoptions: [
    {
      value: "克",
      label: "克"
    },
    {
      value: "千克",
      label: "千克"
    },
    {
      value: "吨",
      label: "吨"
    }
  ],
  photoStatusFlag: false,
  fileStatusFlag: false,
  equipdata: {
    id: "",
    particularYear: "",
    type: "",
    tradeQuota: "",
    price: "",
    ccerValue: "",
    ccerUnitPrice: "",
    amount: "",
    tradeTime: "",
    tradeByName: "",
    createTime: "",
    createByName: "",
    updateByName: "",
    files: []
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    particularYear: "",
    type: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  queryParams2: {
    orderByColumn: "",
    isAsc: "",
    dictWasteCode: "",
    startTime: "",
    endTime: "",
    status: "",
    orderBy: "",
    excludeInboundNumber: [],
    pageNum: 1,
    pageSize: 5
  },
  rules: {
    particularYear: [{ required: true, message: "交易年份不能为空", trigger: "change" }],
    type: [{ required: true, message: "交易类型不能为空", trigger: "change" }],
    tradeByName: [{ required: true, message: "交易人不能为空", trigger: "change" }],
    tradeTime: [{ required: true, message: "交易时间不能为空", trigger: "change" }],
    tradeQuota: [{ required: true, message: "配额交易量不能为空", trigger: "blur" }],
    price: [{ required: true, message: "配额单价不能为空", trigger: "blur" }],
    ccerValue: [{ required: true, message: "CCER交易量不能为空", trigger: "blur" }],
    ccerUnitPrice: [{ required: true, message: "CCER单价不能为空", trigger: "blur" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  carbonEmissionTrendDTOS: [],
  annualQuotaProportionDTO: {},
  userList: []
});
const {
  userList,
  liquidList,
  carbonEmissionTrendDTOS,
  annualQuotaProportionDTO,
  fileStatusFlag,
  facList,
  selectRukuList,
  queryParams,
  queryParams2,
  form,
  rules,
  equipdata,
  rukuList
} = toRefs(data);
const getqueryCategoryList = () => {
  userlistPage({ page: 1, pageSize: 9999, deptNameList: ["ERC&FP"], status: 0 }).then((response: any) => {
    userList.value = response.data.map(item => ({ label: `${item.realName}(${item.username})`, value: item.userId }));
    console.log(response);
  });
  facList.value = [
    { itemName: "创新中心一期", itemValue: "创新中心一期" },
    { itemName: "创新中心二期", itemValue: "创新中心二期" }
  ];
  queryChildByTypeCodeAndItemValue({
    value: "DS01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    liquidList.value = response;
    queryChildByTypeCodeAndItemValue({
      value: "DW01",
      typeCode: "WTTS"
    }).then((response: any) => {
      //console.log(response);
      liquidList.value = [...liquidList.value, ...response];
    });
  });
  //废液代码
};
const getamount = () => {
  if (equipdata.value.tradeQuota != "" && equipdata.value.price != "" && equipdata.value.ccerValue != "" && equipdata.value.ccerUnitPrice != "") {
    equipdata.value.amount =
      Number(equipdata.value.tradeQuota) * Number(equipdata.value.price) + Number(equipdata.value.ccerValue) * Number(equipdata.value.ccerUnitPrice);
  }
};
const selectyinzi = () => {
  innerVisible.value = true;
};
// 新的文件列表
const changeFileList = val => {
  equipdata.value.files = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
const handledelAddPosition = () => {
  equipdata.value.allocationDTOS.unshift({
    level: "",
    initialQuota: null,
    tradeQuota: null,
    ccerValue: null,
    ccerOffsetRatio: ""
  });
  // positionVisible.value = true;
};

const addsave = () => {};
getqueryCategoryList();
function getRukuList() {
  loading.value = true;
  if (dateRange.value != null) {
    queryParams2.value.startTime = dateRange.value[0];
    queryParams2.value.endTime = dateRange.value[1];
  } else {
    queryParams2.value.startTime = "";
    queryParams2.value.endTime = "";
  }
  queryParams2.value.excludeInboundNumber = equipdata.value.details.map(item => item.inboundNumber);

  queryListPageForOutbound(queryParams2.value).then((response: any) => {
    rukuList.value = response.data;
    total2.value = response.total;
    loading.value = false;
  });
}

function getList() {
  loading.value = true;

  quotalistTrade(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}
const removechukuList = () => {
  localStorage.removeItem("chukuList");
};
/** 取消按钮 */

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
function handleQuery2(type) {
  if (type == "search") {
    queryParams2.value.pageNum = 1;
  }
  getRukuList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    particularYear: "",
    type: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

function resetQuery2() {
  queryParams2.value = {
    pageNum: queryParams2.value.pageNum,
    pageSize: queryParams2.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    dictWasteCode: "",
    startTime: "",
    endTime: "",
    status: "",
    orderBy: "",
    excludeInboundNumber: []
  };
  dateRange.value = [];
  handleQuery2("reset");
}
// 增加配额分配
const allocationList = ref([{ level: "", tradeAllocation: 0, tradeCcer: 0 }]);
/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  equipdata.value = {
    id: "",
    particularYear: "",
    type: "",
    tradeQuota: "",
    price: "",
    ccerValue: "",
    ccerUnitPrice: "",
    amount: "",
    tradeTime: "",
    tradeByName: "",
    createTime: "",
    createByName: "",
    updateByName: "",
    files: []
  };
  allocationList.value = [{ level: "", tradeAllocation: 0, tradeCcer: 0 }];
}

const handleDetail = async val => {
  buttonTitle.value = "详情";
  detailVisible.value = true;
  // addVisible.value = true;
  const data = await quotadetailTrade({ id: val });
  console.log(`output->data`, data);
  equipdata.value = data;
  if (data?.files && data?.files.length > 0) {
    data?.files.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.files = data?.files;
  } else {
    equipdata.value.files = [];
  }
  allocationList.value = data.quotaTradeAllocationDTOS;
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  addVisible.value = true;
  const data = await quotadetailTrade({ id: val });
  console.log(data);
  equipdata.value = data;
  equipdata.value.particularYear = data.particularYear.toString();
  if (data?.files && data?.files.length > 0) {
    data?.files.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.files = data?.files;
  } else {
    equipdata.value.files = [];
  }
  allocationList.value = data.quotaTradeAllocationDTOS;
};
/** 多选框选中数据 */
function handleSelectionChange2(selection) {
  // console.log(selection);
  selectRukuList.value = selection;
}

// const addRukudetails = () => {
//   equipdata.value.details = [...equipdata.value.details, ...selectRukuList.value];
//   let seenIds = new Set();
//   let uniqueArr = [];
//   equipdata.value.details.forEach(obj => {
//     if (!seenIds.has(obj.inboundNumber)) {
//       uniqueArr.push(obj);
//       seenIds.add(obj.inboundNumber);
//     }
//   });
//   equipdata.value.details = [];
//   if (setChukuList(uniqueArr) == true) {
//     progressVisible.value = false;
//     equipdata.value.details = uniqueArr;
//   }
// };

let setChukuList = uniqueArr => {
  if (uniqueArr.length === 0) {
    PxMessage({
      message: "请选择要出库的数据",
      type: "error"
    });
    return false;
  }
  const firstname = uniqueArr[0].wasteName;
  for (let i = 1; i < uniqueArr.length; i++) {
    if (uniqueArr[i].wasteName != firstname) {
      PxMessage({
        message: "请选择相同的废弃物",
        type: "error"
      });
      return false;
    }
  }
  return true;
};

const handleDeleteRuku = row => {
  // console.log(row);
  equipdata.value.details = equipdata.value.details.filter(item => item != row);
};
/** 提交按钮 */
function saveFlg(arr): boolean {
  for (const item of arr) {
    if (item.level == "" || item.initialQuota == null || item.tradeQuota == null || item.ccerValue == null || item.ccerOffsetRatio == null) {
      return false;
    }
    return true;
  }
}
function allocationPass() {
  const totalTradeAllocation = allocationList.value.reduce((prev, cur) => {
    return prev + cur.tradeAllocation;
  }, 0);
  const totalCcerValue = allocationList.value.reduce((prev, cur) => {
    return prev + cur.tradeCcer;
  }, 0);
  console.log(`output->totalTradeAllocation`, totalTradeAllocation);
  console.log(`output->totalCcerValue`, totalCcerValue);
  if (totalTradeAllocation != equipdata.value.tradeQuota) {
    PxMessage({
      message: "分配的配额与交易的配额不相等",
      type: "error"
    });
    return false;
  }
  if (totalCcerValue != equipdata.value.ccerValue) {
    PxMessage({
      message: "分配的CCER与交易的CCER不相等",
      type: "error"
    });
    return false;
  }
  return true;
}
const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  // 增加分配判断逻辑
  if (!allocationPass()) {
    return false;
  }
  await formEl.validate(async valid => {
    if (valid) {
      const params = {
        particularYear: Number(equipdata.value.particularYear),
        type: equipdata.value.type,
        tradeQuota: equipdata.value.tradeQuota,
        price: equipdata.value.price,
        ccerValue: equipdata.value.ccerValue,
        ccerUnitPrice: equipdata.value.ccerUnitPrice,
        amount: equipdata.value.amount,
        tradeTime: equipdata.value.tradeTime,
        tradeByName: equipdata.value.tradeByName,
        createByName: JSON.parse(localStorage.getItem("userInfo")).username,
        files: equipdata.value.files,
        quotaTradeAllocationDTOS: allocationList.value
      };
      if (buttonTitle.value == "新增") {
        quotaupdateTrade(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        getList();
      } else {
        const params2 = {
          id: equipdata.value.id,
          particularYear: Number(equipdata.value.particularYear),
          type: equipdata.value.type,
          tradeQuota: equipdata.value.tradeQuota,
          price: equipdata.value.price,
          ccerValue: equipdata.value.ccerValue,
          ccerUnitPrice: equipdata.value.ccerUnitPrice,
          amount: equipdata.value.amount,
          tradeTime: equipdata.value.tradeTime,
          tradeByName: equipdata.value.tradeByName,
          updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
          files: equipdata.value.files,
          quotaTradeAllocationDTOS: allocationList.value
        };
        quotaupdateTrade(params2).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        getList();
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await quotadeleteTrade({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  const dictIds = [];
  dictIds.push(...ids.value);
  const params = { ids: dictIds };
  proxy.download("post", "/operation/api/v1/water/hazardWasteOut/export", params, "危险废弃物出库.xlsx");
}
getList();
/**------------------------------------- 分配信息 ---------------------------------------- */

function addAllocation() {
  allocationList.value.push({ level: "", tradeAllocation: 0, tradeCcer: 0 });
}
// function delAllocation(index: number) {
//   allocationList.value.splice(index, 1);
// }
function delAllocation(index) {
  PxMessageBox.confirm("是否确认删除配额分配？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    // type: "warning",
    draggable: true
  })
    .then(async () => {
      if (allocationList.value.length > 1) {
        allocationList.value.splice(index, 1);
        PxMessage({
          message: "删除成功",
          type: "success"
        });
        getList();
      } else {
        PxMessage({
          message: "至少有一个厂区",
          type: "warning"
        });
      }
    })
    .catch(() => {});
}
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;
  padding-bottom: 0;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 266px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.chartDom {
  width: 100%;
  height: 252px;
}

.chart1 {
  float: left;
  width: 312px;
  height: 252px;
  margin-right: 48px;
}

.chart2 {
  float: left;
  width: 370px;
  height: 252px;
}

.chart-title {
  width: 100%;
  font-size: 14px;
  font-weight: 600;
  color: #000;
  text-align: center;
}

:deep(.px-input-number .px-input__inner) {
  text-align: left;
}

:deep(.px-input-number.is-controls-right .px-input__wrapper) {
  padding-left: 8px;
}
</style>
